package serializable.protostuff;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import org.junit.Test;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

public class ProtostuffDemo {
	/**
     * 避免每次序列化都重新申请Buffer空间
     */
    private static Map<Class<?>,LinkedBuffer> classBuffer = new HashMap<Class<?>, LinkedBuffer>(); 
	/**
     * 序列化方法，把指定对象序列化成字节数组
     *
     * @param obj
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        Class<T> clazz = (Class<T>) obj.getClass();
        Schema<T> schema = getSchema(clazz);
        byte[] data;
        try {
        	if(!classBuffer.containsKey(clazz)) {
        		classBuffer.put(clazz, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
        	}
            data = ProtostuffIOUtil.toByteArray(obj, schema, classBuffer.get(clazz));
        } finally {
        	if(classBuffer.get(clazz)!=null) {
        		classBuffer.get(clazz).clear();
        	}
        }

        return data;
    }

    /**
     * 反序列化方法，将字节数组反序列化成指定Class类型
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        Schema<T> schema = getSchema(clazz);
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, obj, schema);
        return obj;
    }
    
    public static <T> T deserialize(InputStream data, Class<T> clazz) throws IOException {
        Schema<T> schema = getSchema(clazz);
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, obj, schema);
        return obj;
    }
    private static Map<Class<?>, Schema<?>> schemaCache = new ConcurrentHashMap<>();
    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> clazz) {
        Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
        if (Objects.isNull(schema)) {
            //这个schema通过RuntimeSchema进行懒创建并缓存
            //所以可以一直调用RuntimeSchema.getSchema(),这个方法是线程安全的
            schema = RuntimeSchema.getSchema(clazz);
            if (Objects.nonNull(schema)) {
                schemaCache.put(clazz, schema);
            }
        }

        return schema;
    }
	
	@Test
	public void serializable() throws IOException {
//		A obj = new A();
//		obj.setA("a");
		
		B obj = new B();
		A a = new A();
		a.setB("b");
		obj.setA(a);
		List<A> as = new ArrayList<>();
		A a2 = new A();
		a2.setA("a");
		as.add(a2);
		A a3 = new A();
		a3.setA("a");
		as.add(a3);
//		obj.setAs(as);
		
		System.out.println(obj);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.protostuff"));
		byte[] data = serialize(obj);
		System.out.println(data.length);
		bos.write(data);
		bos.flush();
		bos.close();
	}
	@Test
	public void deserializable() throws IOException {
		
		B a = deserialize(new FileInputStream("a.protostuff"), B.class);
		System.out.println(a);
	}
}
